<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Role extends Model
{
	use HasFactory;
	
	protected $fillable = ['name','desc'];
	
    public function access()
    {
        return $this->belongsToMany('App\Model\Access');
    }
	
    public function users()
    {
        return $this->hasMany('App\Model\User');
    }
	
    public function menus()
    {
		//获取菜单不需要权限控制的菜单
		$menu=Menu::where("path","<>","")->has('access', '=', 0)->get();

		//获取角色权限关联的菜单
		foreach($this->access->map(function($items, $key){return $items->menus;})->all() as $item){$menu=$menu->concat($item);}

		//获取可用菜单父类菜单
		$menus=Menu::where('id',0);
		foreach(explode(',',$menu->unique('parent_id')->implode('parent_id',',')) as $item){$menus->orWhere('id',$item);}

		$menu=$menu->concat($menus->get());

		return $menu->unique('id')->sortBy("id")->values();
    }
}
